<template>
  <div class="article-edit">
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <h2>加载失败</h2>
      <p>{{ error }}</p>
      <button @click="goBack" class="back-btn">返回</button>
    </div>
    
    <div v-else-if="article" class="edit-container">
      <!-- 编辑头部 -->
      <div class="edit-header">
        <div class="breadcrumb">
          <router-link to="/" class="breadcrumb-link">首页</router-link>
          <span class="breadcrumb-separator">></span>
          <span class="breadcrumb-current">编辑文章</span>
        </div>
        
        <h1 class="edit-title">编辑文章</h1>
        
        <div class="edit-actions">
          <button @click="goBack" class="action-btn secondary">
            <i class="fas fa-arrow-left"></i>
            返回
          </button>
          <button @click="previewArticle" class="action-btn info">
            <i class="fas fa-eye"></i>
            预览
          </button>
          <button @click="saveArticle" :disabled="saving" class="action-btn primary">
            <i class="fas fa-save"></i>
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
      
      <!-- 编辑和预览区域 -->
      <div class="edit-preview-container">
        <!-- 左侧编辑区域 -->
        <div class="edit-section">
          <div class="section-header">
            <h3>编辑</h3>
            <el-button @click="togglePreview" :type="showPreview ? 'primary' : 'default'" size="small">
              <i class="fas fa-eye"></i>
              {{ showPreview ? '隐藏预览' : '显示预览' }}
            </el-button>
          </div>
          
          <div class="edit-form">
            <el-form
              :model="articleForm"
              label-width="68px"
              :rules="formRules"
              ref="formRef"
            >
              <el-form-item label="标题" prop="title" required>
                <el-input 
                  v-model="articleForm.title" 
                  placeholder="请输入文章标题"
                  size="large"
                />
              </el-form-item>
              
              <el-form-item label="作者" prop="authorId" required>
                <el-select 
                  v-model="articleForm.authorId" 
                  placeholder="请选择作者" 
                  style="width: 100%"
                  size="large"
                >
                  <el-option 
                    v-for="user in users" 
                    :key="user.id" 
                    :label="user.fullName || user.username"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="分类">
                <el-select 
                  v-model="articleForm.categories" 
                  multiple 
                  placeholder="请选择分类（可多选）" 
                  style="width: 100%"
                  size="large"
                >
                  <el-option 
                    v-for="category in categories" 
                    :key="category.dictCode" 
                    :label="category.dictLabel"
                    :value="category.dictValue"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="articleForm.status" size="large">
                  <el-radio label="DRAFT">草稿</el-radio>
                  <el-radio label="PUBLISHED">已发布</el-radio>
                  <el-radio label="ARCHIVED">已归档</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="内容" prop="content" required class="content-form-item">
                <el-input 
                  v-model="articleForm.content" 
                  type="textarea"
                  placeholder="请输入文章内容（支持Markdown格式）"
                  :rows="textareaRows"
                  resize="vertical"
                  class="content-textarea"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <!-- 右侧预览区域 -->
        <div v-if="showPreview" ref="previewSection" class="preview-section">
          <div class="section-header">
            <h3>预览</h3>
            <el-button @click="openPreviewInNewTab" type="info" size="small">
              <i class="fas fa-external-link-alt"></i>
              新窗口预览
            </el-button>
          </div>
          
          <div class="preview-content">
            <div class="preview-article">
              <h1 class="preview-title">{{ articleForm.title || '文章标题' }}</h1>
              
              <div class="preview-meta">
                <div class="meta-item">
                  <span class="meta-label">作者：</span>
                  <span class="meta-value">{{ getAuthorName(articleForm.authorId) }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">状态：</span>
                  <span class="meta-status" :class="articleForm.status.toLowerCase()">
                    {{ getStatusText(articleForm.status) }}
                  </span>
                </div>
              </div>
              
              <div v-if="articleForm.categories && articleForm.categories.length > 0" class="preview-categories">
                <div class="tags">
                  <span 
                    v-for="label in getCategoryLabels(articleForm.categories)" 
                    :key="label"
                    class="tag"
                  >
                    {{ label }}
                  </span>
                </div>
              </div>
              
              <!-- 文章正文 -->
              <div class="preview-article-body">
                <div class="content" v-html="renderMarkdown(articleForm.content)"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { articleAPI } from '@api/article.js'
import { userAPI } from '@api/user.js'
import { dictAPI } from '@api/dict.js'
import { ElMessage } from 'element-plus'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

export default {
  name: 'ArticleEdit',
  data() {
    return {
      article: null,
      users: [],
      categories: [],
      loading: true,
      saving: false,
      error: null,
      showPreview: true,
      previewHeight: 0,
      resizeObserver: null,
      articleForm: {
        title: '',
        content: '',
        authorId: '',
        status: 'DRAFT',
        categories: []
      },
      formRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 200, message: '标题长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
          { min: 10, message: '内容至少需要 10 个字符', trigger: 'blur' }
        ],
        authorId: [
          { required: true, message: '请选择作者', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    currentUser() {
      return this.$store.state.user
    },
    canEdit() {
      return this.currentUser && 
             (this.currentUser.id === this.article?.authorId || this.currentUser.isAdmin)
    },
    textareaRows() {
      console.log(this.previewHeight)
      // 根据预览区域高度动态计算文本域行数
      if (this.previewHeight > 0) {
        // 每行大约22px高度，减去一些边距
        const availableHeight = this.previewHeight - 100 // 减去标题、元数据等的高度
        const calculatedRows = Math.max(10, Math.floor(availableHeight / 22))
        return Math.min(calculatedRows, 100) // 限制最大行数
      }
      return 20 // 默认行数
    }
  },
  watch: {
    showPreview(newVal) {
      if (newVal) {
        // 显示预览时重新测量高度
        this.$nextTick(() => {
          setTimeout(() => {
            this.updatePreviewHeight()
            this.setupResizeObserver()
          }, 50)
        })
      } else {
        // 隐藏预览时清理ResizeObserver
        if (this.resizeObserver) {
          this.resizeObserver.disconnect()
          this.resizeObserver = null
        }
      }
    }
  },
  async mounted() {
    await this.loadArticle()
    await this.loadUsers()
    await this.loadCategories()
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
    // 延迟测量预览区域高度，确保DOM完全渲染
    setTimeout(() => {
      this.updatePreviewHeight()
      this.setupResizeObserver()
    }, 100)
  },
  updated() {
    this.highlightCode()
  },
  beforeUnmount() {
    // 清理事件监听器
    window.removeEventListener('resize', this.handleResize)
    // 清理ResizeObserver
    if (this.resizeObserver) {
      this.resizeObserver.disconnect()
    }
  },
  methods: {
    setupResizeObserver() {
      // 使用ResizeObserver监听预览区域大小变化
      if (window.ResizeObserver) {
        this.resizeObserver = new ResizeObserver((entries) => {
          for (let entry of entries) {
            this.previewHeight = entry.contentRect.height
            console.log('Preview height updated by ResizeObserver:', this.previewHeight)
          }
        })
        
        const previewSection = this.$refs.previewSection
        if (previewSection) {
          this.resizeObserver.observe(previewSection)
        }
      }
    },
    
    updatePreviewHeight() {
      // 测量预览区域的高度
      this.$nextTick(() => {
        const previewSection = this.$refs.previewSection
        if (previewSection) {
          this.previewHeight = previewSection.offsetHeight
          console.log('Preview height updated:', this.previewHeight)
        } else {
          console.log('Preview section not found')
        }
      })
    },
    
    handleResize() {
      // 窗口大小变化时重新测量预览区域高度
      this.updatePreviewHeight()
    },
    
    async loadArticle() {
      this.loading = true
      this.error = null
      
      try {
        const articleId = this.$route.params.id
        const response = await articleAPI.getArticleById(articleId)
        
        if (response.data.success) {
          this.article = response.data.data
          
          // 检查编辑权限
          if (!this.canEdit) {
            this.error = '您没有权限编辑此文章'
            return
          }
          
          // 填充表单数据
          this.articleForm = {
            title: this.article.title,
            content: this.article.content,
            authorId: this.article.authorId,
            status: this.article.status,
            categories: this.article.categories ? this.article.categories.split(',').map(c => c.trim()) : []
          }
        } else {
          this.error = response.data.message || '文章不存在'
        }
      } catch (error) {
        console.error('加载文章失败:', error)
        this.error = '加载文章失败'
      } finally {
        this.loading = false
      }
    },
    
    async loadUsers() {
      try {
        const response = await userAPI.getAllUsers()
        if (response.data.success) {
          this.users = response.data.data
        }
      } catch (error) {
        console.error('加载用户失败:', error)
      }
    },
    
    async loadCategories() {
      try {
        const response = await dictAPI.getArticleCategories()
        if (response.data.success) {
          this.categories = response.data.data
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    async saveArticle() {
      // 表单验证
      if (!this.$refs.formRef) return
      
      try {
        await this.$refs.formRef.validate()
      } catch (error) {
        ElMessage.warning('请填写所有必填项')
        return
      }
      
      this.saving = true
      
      try {
        // 处理分类数据，将数组转换为逗号分隔的字符串
        const formData = {
          ...this.articleForm,
          categories: this.articleForm.categories.join(',')
        }
        
        const response = await articleAPI.updateArticle(this.article.id, formData)
        
        if (response.data.success) {
          ElMessage.success('文章更新成功')
          // 重新加载文章数据以更新页面
          await this.loadArticle()
        } else {
          ElMessage.error(response.data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存文章失败:', error)
        ElMessage.error('保存失败')
      } finally {
        this.saving = false
      }
    },
    
    previewArticle() {
      // 跳转到预览页面
      this.$router.push(`/preview/${this.article.id}`)
    },
    
    togglePreview() {
      this.showPreview = !this.showPreview
      if (this.showPreview) {
        // 显示预览时重新测量高度
        this.$nextTick(() => {
          setTimeout(() => {
            this.updatePreviewHeight()
          }, 50)
        })
      }
    },
    
    openPreviewInNewTab() {
      // 在新标签页中打开预览
      const previewUrl = `/preview/${this.article.id}`
      window.open(previewUrl, '_blank')
    },
    
    getAuthorName(authorId) {
      if (!authorId) return '请选择作者'
      const user = this.users.find(u => u.id === authorId)
      return user ? (user.fullName || user.username) : '未知作者'
    },
    
    getStatusText(status) {
      const statusMap = {
        'DRAFT': '草稿',
        'PUBLISHED': '已发布',
        'ARCHIVED': '已归档'
      }
      return statusMap[status] || status
    },
    
    getCategoryLabels(categories) {
      if (!categories || categories.length === 0) return []
      return categories.map(categoryValue => {
        const category = this.categories.find(c => c.dictValue === categoryValue)
        return category ? category.dictLabel : categoryValue
      })
    },
    
    renderMarkdown(content) {
      if (!content) return ''
      
      // 简单的Markdown到HTML转换
      let html = content
      
      // 处理标题
      html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>')
      html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>')
      html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>')
      
      // 处理代码块
      html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>')
      html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
      
      // 处理粗体和斜体
      html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
      
      // 处理列表
      html = html.replace(/^- (.*$)/gim, '<li>$1</li>')
      html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
      
      // 处理段落
      html = html.replace(/\n\n/g, '</p><p>')
      html = '<p>' + html + '</p>'
      
      return html
    },
    
    highlightCode() {
      this.$nextTick(() => {
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightElement(block)
        })
      })
    },
    
    goBack() {
      // 如果是从管理页面打开的，返回管理页面
      if (document.referrer && document.referrer.includes('/admin')) {
        this.$router.push('/admin/articles')
      } else {
        this.$router.go(-1)
      }
    }
  }
}
</script>

<style scoped>
@import '@/styles/components/article.scss';

/* ArticleEdit 特有的样式 */
.article-edit {
  min-height: 100vh;
  padding: 0;
}

.edit-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 2rem;
}

.edit-header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 2rem;
  margin-bottom: 2rem;
}

.edit-title {
  font-size: 2rem;
  font-weight: 700;
  background: var(--gradient-rainbow);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 2rem;
  line-height: 1.3;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.edit-actions {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.action-btn.info {
  background: #17a2b8;
  color: white;
}

.action-btn.info:hover:not(:disabled) {
  background: #138496;
}

.edit-preview-container {
  display: flex;
  gap: 2rem;
  align-items: stretch;
  width: 100%;
  min-height: 80vh;
}

.edit-section {
  flex: 1;
  min-width: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.preview-section {
  flex: 1;
  min-width: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #5a5a5a;
}

.section-header h3 {
  margin: 0;
  color: #e8e8e8;
  font-size: 1.2rem;
  font-weight: 600;
}

.edit-form {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 2rem;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.preview-content {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 2rem;
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.preview-article {
  color: #e0e0e0;
  flex: 1;
  display: flex;
  flex-direction: column;
  line-height: 1.8;
  font-size: 1.1rem;
}

.preview-article-body {
  margin-bottom: 3rem;
}


.preview-title {
  font-size: 2.5rem;
  font-weight: 700;
  background: var(--gradient-rainbow);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  margin-bottom: 2rem;
  text-align: center;
  position: relative;
  display: inline-block;
  width: 100%;
}

.preview-meta {
  display: flex;
  gap: 2rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.preview-meta .meta-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.preview-meta .meta-label {
  color: #97dc99;
  font-weight: 600;
}

.preview-meta .meta-value {
  color: #ffffff;
  font-weight: 700;
  background: var(--gradient-rainbow);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.preview-meta .meta-status {
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.preview-meta .meta-status.published {
  background: #88c057;
  color: #ffffff;
}

.preview-meta .meta-status.draft {
  background: #fff3cd;
  color: #856404;
}

.preview-meta .meta-status.archived {
  background: #f8d7da;
  color: #721c24;
}

.preview-categories {
  margin-bottom: 1.5rem;
}

.preview-categories .tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.preview-categories .tag {
  display: inline-block;
  background: linear-gradient(135deg, rgba(92, 225, 255, 0.2) 0%, rgba(160, 226, 95, 0.2) 100%);
  color: var(--color-primary-light);
  padding: 0.3rem 0.8rem;
  border-radius: var(--radius-xl);
  font-size: 0.8rem;
  border: 1px solid rgba(92, 225, 255, 0.4);
  font-weight: 600;
}

/* Element Plus 样式覆盖 */
.edit-form :deep(.el-form-item__label) {
  color: #e8e8e8;
  font-weight: 600;
}

.edit-form :deep(.el-input__inner) {
  border-color: #5a5a5a;
  color: #e8e8e8;
}

.edit-form :deep(.el-input__inner:focus) {
  border-color: #4fc1ff;
  box-shadow: 0 0 0 2px rgba(79, 193, 255, 0.2);
}

.edit-form :deep(.el-textarea__inner) {
  background-color: #2a2a2a;
  border-color: #5a5a5a;
  color: #e8e8e8;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  line-height: 1.6;
}

.edit-form :deep(.el-textarea__inner:focus) {
  border-color: #4fc1ff;
  box-shadow: 0 0 0 2px rgba(79, 193, 255, 0.2);
}

.edit-form :deep(.el-select .el-input__inner) {
  border-color: #5a5a5a;
  color: #e8e8e8;
}

.edit-form :deep(.el-radio__label) {
  color: #e8e8e8;
}

.edit-form :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #4fc1ff;
  border-color: #4fc1ff;
}

.edit-form :deep(.el-option) {
  color: #e8e8e8;
}

/* 内容表单项样式 */
.content-form-item {
  flex: 1;
}

.content-textarea :deep(.el-textarea__inner) {
  resize: vertical;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  line-height: 1.6;
}

@media (max-width: 768px) {
  .edit-container {
    padding: 1rem;
    max-width: 100%;
  }
  
  .edit-header {
    padding: 1.5rem;
  }
  
  .edit-title {
    font-size: 1.5rem;
  }
  
  .edit-actions {
    flex-direction: column;
  }
  
  .action-btn {
    justify-content: center;
  }
  
  .edit-preview-container {
    flex-direction: column;
    gap: 1rem;
    width: 100%;
    min-height: auto;
  }
  
  .edit-section {
    width: 100%;
    min-height: 50vh;
  }
  
  .preview-section {
    width: 100%;
    min-height: 50vh;
  }
  
  .edit-form {
    padding: 1.5rem;
  }
  
  .preview-content {
    padding: 1.5rem;
    min-height: 50vh;
  }
  
  .preview-title {
    font-size: 1.5rem;
  }
  
  .preview-meta {
    flex-direction: column;
    gap: 0.8rem;
  }
}
</style>
